<?php
error_reporting ( E_ALL & ~E_NOTICE );

class Template
{
	
	private $DF;
	
	private $vars = array ( );
	
	private $template = NULL;
	
	/*------------------------------------------------
	 Constructor
	 $DF the core global DF object
	--------------------------------------------------*/
	function __construct ( $DF, $_0 = NULL )
	{
		$this->DF = $DF;
		
		$this->template = $_0;
	}
	
	/*------------------------------------------------
	 Select the template to work with
	 $_0 string name of template file
	--------------------------------------------------*/
	public function selectTemplate ( $_0 )
	{
		$this->template = $_0;
	}
	
	/*------------------------------------------------
	 Magically set vars :)
	 $_0 var name
	 $_1 var value
	--------------------------------------------------*/
	public function set ( $_0, $_1 )
	{
		# If value is an object ( most likely another template )
		if ( is_object ( $_1 ) )
		{
			#echo "var: " . $_1 . "<br>";
			$this->vars[$_0] = $_1->fetch ( );
		}
		else
		{
			$this->vars[$_0] = $_1;
		}
	}

	/*------------------------------------------------
	 Empty all of the vars. You may want to do this
	 after you load a template.
	--------------------------------------------------*/
	public function emptyVars ( )
	{
		$this->vars = array ( );
	}
	
	/*------------------------------------------------
	 Set the template vars and load the template
	 $_0 name of template file
	--------------------------------------------------*/
	function show ( $_0 )
	{
		$path = DIR_APP_VIEWS . $_0 . '.php';
	
		if ( file_exists ( $path ) === FALSE )
		{
			throw new Exception ( 'Template not found in '. $path );
			
			return FALSE;
		}
	
		# Load/set the vars
		foreach ( $this->vars AS $key => $value )
		{
			$$key = $value;
		}
		
		include $path;
	}
	
	/*------------------------------------------------
	 Fetch the parsed template into a string var
	 $_0 name of template file
	--------------------------------------------------*/
	function fetch ( $_0 = NULL )
	{
		# If a template file name has not been passed to
		# this method, use $this->template ( hopefully 
		# $this->template is set )
		if ( empty ( $_0 ) )
		{
			$_0 = $this->template;
		}
		
		# Start output buffer
		ob_start ( );
		
		# Include the template
		$this->show ( $_0 );
		
		# Get output buffer contents into a var
		$contents = ob_get_contents ( );
		
		# Close and clean the output buffer
		ob_end_clean ( );
		
		return $contents;
	}
}
?>